﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Activities;
using VMware.Vim;

namespace VMWareActivities
{
    using Microsoft.TeamFoundation.Build.Client;

    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class RestoreSnapshotAcitvity : CodeActivity
    {
        [RequiredArgument()]
        public InArgument<string> SnapshotPath { get; set; }
        public InArgument<VirtualMachine> VirtualMachine { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string snapshotPath = context.GetValue(this.SnapshotPath);
            VirtualMachine virtualMachine = context.GetValue(this.VirtualMachine);

            ManagedObjectReference snapshot = FindSnapshot(virtualMachine.Snapshot.RootSnapshotList, snapshotPath);
            VirtualMachineSnapshot vms = new VirtualMachineSnapshot(virtualMachine.Client, snapshot);
            vms.RevertToSnapshot(virtualMachine.Client.GetView(virtualMachine.Runtime.Host, null).MoRef, false);
        }

        /// <summary>
        /// Finds the snapshot.
        /// </summary>
        /// <param name="root">The root.</param>
        /// <param name="snapshotPath">The snapshot path.</param>
        /// <returns></returns>
        private ManagedObjectReference FindSnapshot(VirtualMachineSnapshotTree[] root, string snapshotPath)
        {
            foreach (VirtualMachineSnapshotTree tree in root)
            {
                if (tree.Name.Equals(snapshotPath, StringComparison.OrdinalIgnoreCase))
                {
                    return tree.Snapshot;
                }
            }

            foreach (VirtualMachineSnapshotTree tree in root)
            {
                ManagedObjectReference snap = null;
                if (tree.ChildSnapshotList != null)
                {
                    snap = FindSnapshot(tree.ChildSnapshotList, snapshotPath);
                }
                if (snap != null)
                {
                    return snap;
                }
            }
            return null;
        }
    }
}
